package logic

import (
	"context"
	"fmt"
	"luck/model/cache"
	"strconv"

	"luck/luckrpc/internal/svc"
	"luck/luckrpc/luckrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartListLogic {
	return &CartListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartListLogic) CartList(in *luckrpc.CartListRequest) (*luckrpc.CartListResponse, error) {
	// todo: add your logic here and delete this line
	var cart []*luckrpc.CartList
	var total = 0.0
	key := fmt.Sprintf("cart:%d:*", in.UserId)
	keys, err := cache.Rdb.Keys(l.ctx, key).Result()
	if err != nil {
		return nil, fmt.Errorf("获取购物车失败")
	}
	for _, k := range keys {
		productMap, _ := cache.Rdb.HGetAll(l.ctx, k).Result()
		productId, _ := strconv.Atoi(productMap["productId"])
		Price, _ := strconv.ParseFloat(productMap["Price"], 64)
		Stock, _ := strconv.Atoi(productMap["Stock"])
		quantity, _ := strconv.Atoi(productMap["quantity"])
		subtotal := float64(quantity) * Price
		total += subtotal
		list := luckrpc.CartList{
			UserId:    in.UserId,
			Name:      productMap["Name"],
			Price:     float32(Price),
			Stock:     int64(Stock),
			ImageUrl:  productMap["ImageUrl"],
			ProductId: int64(productId),
			Quantity:  int64(quantity),
		}
		cart = append(cart, &list)
	}
	return &luckrpc.CartListResponse{
		List:        cart,
		TotalAmount: float32(total),
	}, nil
}
